﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HPortal.Lib;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;

namespace HPortal.Backend
{
    public partial class DetaiChitiet : System.Web.UI.Page
    {
        protected int DetaiID;
        protected string Directory = System.Configuration.ConfigurationManager.AppSettings["OsPortal.PortalCore.WebPathUserFilesUpload"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
            DetaiID = HtmlHelper.GetIdFromRequestString("DetaiID", 0);
            if (!IsPostBack)
            {
                cmdEditTiendo.Enabled = false;
                BindCombo();
                if (DetaiID != 0)
                {
                    Session["DetaiID"] = DetaiID.ToString();
                    BindData();
                    cmdUpdate.Text = "Cập nhật thông tin đề tài";
                    cmdDelete.Enabled = true;
                    rBaocao.Visible = true;
                    rTiendo.Visible = true;
                }
                else
                {
                    cmdUpdate.Text = "Thêm mới đề tài";
                    cmdDelete.Enabled = false;
                    rBaocao.Visible = false;
                    rTiendo.Visible = false;
                }
                if (CheckPermission() == false)
                    Response.Redirect("DetaiList.aspx");
            }
        }
        private void BindData()
        {
            DataTable art = DatabaseHelper.Select("[KH_ChitietDetai1] " + DetaiID);
            txtMaso.Text = art.Rows[0]["Maso"].ToString();
            txtTenDetai.Text = art.Rows[0]["Tendetai"].ToString();
            txtMuctieu.Text = art.Rows[0]["Muctieu"].ToString();
            txtKetqua.Text = art.Rows[0]["Ketqua"].ToString();
            cboChunhiem.SelectedValue = art.Rows[0]["ChutriID"].ToString();
            cboLinhvuc.SelectedValue = art.Rows[0]["LinhvucID"].ToString();
            cboLoai.SelectedValue = art.Rows[0]["LoaiID"].ToString();
            cboTrangthai.SelectedValue = art.Rows[0]["Trangthai"].ToString();
            cboChunhiem.SelectedValue = art.Rows[0]["ChutriID"].ToString();
            cboCap.SelectedValue = art.Rows[0]["CapID"].ToString();
            cboDonvi.SelectedValue = art.Rows[0]["DonviID"].ToString();

            DataTable dtBaocao = DatabaseHelper.Select("[KH_BaocaoDetai] " + DetaiID);
            grvArticlelList.DataSource = dtBaocao;
            grvArticlelList.DataBind();

            DataTable dtTiendo = DatabaseHelper.Select("[KH_TiendoDetai] " + DetaiID);
            grvTiendo.DataSource = dtTiendo;
            grvTiendo.DataBind();
        }
        private void BindCombo()
        {
            cboLinhvuc.DataSource = DatabaseHelper.Select("Select LinhvucID,Ten From KH_Linhvuc");
            cboLinhvuc.DataTextField = "Ten";
            cboLinhvuc.DataValueField = "LinhvucID";
            cboLinhvuc.DataBind();

            cboLoai.DataSource = DatabaseHelper.Select("Select LoaiID,TenLoai From KH_Loai");
            cboLoai.DataTextField = "TenLoai";
            cboLoai.DataValueField = "LoaiID";
            cboLoai.DataBind();

            cboCap.DataSource = DatabaseHelper.Select("Select CapID,TenCap From KH_Cap");
            cboCap.DataTextField = "TenCap";
            cboCap.DataValueField = "CapID";
            cboCap.DataBind();

            cboChunhiem.DataSource = DatabaseHelper.Select("Select NguoidungID,HoTen From KH_Nguoidung ORDER BY Hoten DESC");
            cboChunhiem.DataTextField = "HoTen";
            cboChunhiem.DataValueField = "NguoidungID";
            cboChunhiem.DataBind();

            cboDonvi.DataSource = DatabaseHelper.Select("Select DonviID,Ten From KH_Donvi ORDER BY Ten DESC");
            cboDonvi.DataTextField = "Ten";
            cboDonvi.DataValueField = "DonviID";
            cboDonvi.DataBind();
        }

        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            if (DetaiID != 0)
                DatabaseHelper.Execute("[KH_UpdateDetai] " + DetaiID + "," + DatabaseHelper.EscapeQuote(txtMaso.Text) + "," + DatabaseHelper.EscapeQuoteUnicode(txtTenDetai.Text) + "," + DatabaseHelper.EscapeQuoteUnicode(txtMuctieu.Text) + "," + DatabaseHelper.EscapeQuoteUnicode(txtKetqua.Text) + "," + cboChunhiem.SelectedValue + "," + cboCap.SelectedValue + "," + cboLoai.SelectedValue + "," + cboLinhvuc.SelectedValue + "," + cboTrangthai.SelectedValue);
            else
            {
                DatabaseHelper.Execute("[KH_InsertDetai] " + DatabaseHelper.EscapeQuote(txtMaso.Text) + "," + DatabaseHelper.EscapeQuoteUnicode(txtTenDetai.Text) + "," + DatabaseHelper.EscapeQuoteUnicode(txtMuctieu.Text) + "," + DatabaseHelper.EscapeQuoteUnicode(txtKetqua.Text) + "," + cboChunhiem.SelectedValue + "," + cboCap.SelectedValue + "," + cboLoai.SelectedValue + "," + cboLinhvuc.SelectedValue + "," + cboTrangthai.SelectedValue);
                DetaiID = int.Parse(DatabaseHelper.Select("select Dbo.LayDetaiID()").Rows[0][0].ToString());
                rBaocao.Visible = true;
                rTiendo.Visible = true;
                Session["DetaiID"] = DetaiID.ToString();
            }
        }

        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            DatabaseHelper.Execute("Delete From Kh_Detai Where DetaiID=" + DetaiID);
            Response.Redirect("DetaiList.aspx");
        }

        protected void cboDonvi_SelectedIndexChanged(object sender, EventArgs e)
        {
            cboChunhiem.DataSource = DatabaseHelper.Select("Select NguoidungID,HoTen From KH_Nguoidung Where DonviID=" + cboDonvi.SelectedValue + " ORDER BY Hoten DESC");
            cboChunhiem.DataTextField = "HoTen";
            cboChunhiem.DataValueField = "NguoidungID";
            cboChunhiem.DataBind();
        }
        private Boolean CheckPermission()
        {
            String VuKHCNRole = System.Configuration.ConfigurationManager.AppSettings["VuKHCNRole"].ToString();
            if (this.Context.User.Identity.IsAuthenticated)
            {
                string[] arrRoleName = Roles.GetRolesForUser(this.Context.User.Identity.Name);
                foreach (string roleName in arrRoleName)
                    if (roleName == VuKHCNRole)
                        return true;
            }
            int userID = DatabaseHelper.SelectScalarInt("Select NguoidungID From KH_Nguoidung Where UserName=N'" + this.Context.User.Identity.Name + "'");
            int userID1 = DatabaseHelper.SelectScalarInt("Select ChutriID From KH_Detai Where DetaiID=" + DetaiID);
            if (userID == userID1)
                return true;
            return false;
        }

        protected void cmdThemTiendo_Click(object sender, EventArgs e)
        {
            DetaiID = int.Parse(Session["DetaiID"].ToString());
            DatabaseHelper.Execute("[KH_InsertTiendo] " + DetaiID.ToString() + "," + DatabaseHelper.EscapeQuote(txtNam.Text) + "," + DatabaseHelper.EscapeQuote(txtKinhphi.Text));
      
            DataTable dtTiendo = DatabaseHelper.Select("[KH_TiendoDetai] " + DetaiID);
            grvTiendo.DataSource = dtTiendo;
            grvTiendo.DataBind();
        }

        protected void grvArticlelList_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        protected void grvTiendo_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void lnkChonTiendo_Click(object sender, EventArgs e)
        {
            string TiendoID = ((LinkButton)sender).CommandArgument;
            DataTable t = DatabaseHelper.Select("Select * From KH_Tiendo Where TiendoID=" + TiendoID);
            txtNam.Text = t.Rows[0]["Nam"].ToString();
            txtKinhphi.Text = t.Rows[0]["Kinhphi"].ToString();
            cmdEditTiendo.Enabled = true;
            cmdEditTiendo.CommandArgument = TiendoID;
        }

        protected void lnkXoaTiendo_Click(object sender, EventArgs e)
        {
            string TiendoID = ((LinkButton)sender).CommandArgument;
            DatabaseHelper.Select("Delete From KH_Tiendo Where TiendoID=" + TiendoID);

            DataTable dtTiendo = DatabaseHelper.Select("[KH_TiendoDetai] " + DetaiID);
            grvTiendo.DataSource = dtTiendo;
            grvTiendo.DataBind();
        }

        protected void cmdEditTiendo_Click(object sender, EventArgs e)
        {
            string TiendoID = ((Button)sender).CommandArgument;
            DatabaseHelper.Select("Update KH_Tiendo Set Nam=" + DatabaseHelper.EscapeQuote(txtNam.Text) + ",Kinhphi=" +  DatabaseHelper.EscapeQuote(txtKinhphi.Text) + " Where TiendoID=" + TiendoID);

            DataTable dtTiendo = DatabaseHelper.Select("[KH_TiendoDetai] " + int.Parse(Session["DetaiID"].ToString()));
            grvTiendo.DataSource = dtTiendo;
            grvTiendo.DataBind();
        }

        protected void cmdInsert_Click(object sender, EventArgs e)
        {
            bool fileUploadisNull = true;
            string FileName = string.Empty;
            int DocumentSize = 0;
            if ((flUpload.PostedFile != null) && (flUpload.PostedFile.ContentLength != 0))
            {
                FileName = flUpload.PostedFile.FileName;
                string FileType = flUpload.PostedFile.ContentType;
                byte[] FileContent = new byte[flUpload.PostedFile.ContentLength];
                this.flUpload.PostedFile.InputStream.Read(FileContent, 0, FileContent.Length);
                DocumentSize = FileContent.Length / 1000;
                fileUploadisNull = false;
            }

            string Title = txtTitle.Text.Replace("'", "''");
            if (!fileUploadisNull)
            {
                string FileType = flUpload.PostedFile.ContentType;
                string FileExt = FileName.Substring(FileName.LastIndexOf(".") + 1);
                int UploadID = DatabaseHelper.InsertIdentity(new string[] { "N@FileType", "@FileExt", "N@Title", "N@AuthorName", "@DocumentSize" },
                    new string[] { FileType, FileExt, Title, Context.User.Identity.Name, DocumentSize.ToString() }, "UploadFile");
                this.UploadFile(flUpload, UploadID.ToString() + "." + FileExt);
                DatabaseHelper.Insert("INSERT INTO [KH_Baocao] ([UploadFileID],[DetaiID]) VALUES (" + UploadID + "," + Session["DetaiID"].ToString() + ")");
            }
            DataTable dtBaocao = DatabaseHelper.Select("[KH_BaocaoDetai] " + DetaiID);
            grvArticlelList.DataSource = dtBaocao;
            grvArticlelList.DataBind();
        }
        public void UploadFile(System.Web.UI.HtmlControls.HtmlInputFile HtmlFullFileUpload, string FileName)
        {
            string strPath = System.IO.Path.GetFileName(FileName);
            string ServerPath = System.Web.HttpContext.Current.Server.MapPath(Directory + "\\" + strPath);
            HtmlFullFileUpload.PostedFile.SaveAs(ServerPath);
        }

        protected void lnkChonBaocao_Click(object sender, EventArgs e)
        {
            string BaocaoID = ((LinkButton)sender).CommandArgument;
            DatabaseHelper.Select("Delete From KH_Baocao Where BaocaoID=" + BaocaoID);

            DataTable dtBaocao = DatabaseHelper.Select("[KH_BaocaoDetai] " + DetaiID);
            grvArticlelList.DataSource = dtBaocao;
            grvArticlelList.DataBind();
        }
    }
}